#!/usr/bin/python3

# Copyright (c) 2020-2021 Fpemud <fpemud@sina.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.


import os
import abc
import json
import functools


class AppBase(abc.ABC):

    @abc.abstractmethod
    def get_process_hierachy(self, snapshot):
        pass

    @abc.abstractmethod
    def check(self, snapshot, pid, descendant_pids):
        pass


class StraitBase(abc.ABC):

    @abc.abstractmethod
    def check(self, snapshot, pid, descendant_pids):
        pass


class PluginUtil:

    @functools.cache
    @staticmethod
    def getPluginNames(pluginType):
        assert pluginType in ["app", "strait"]

        selfDir = os.path.dirname(os.path.realpath(__file__))
        pluginDir = os.path.join(selfDir, pluginType + "s")
        ret = [x for x in os.listdir(pluginDir) if not x.startswith("__")]
        assert all([os.path.isdir(os.path.join(pluginDir, x)) for x in ret])
        ret.sort()
        return ret

    @functools.cache
    @staticmethod
    def getPlugin(pluginType, pluginName):
        assert pluginType in ["app", "strait"]

        selfDir = os.path.dirname(os.path.realpath(__file__))
        pluginDir = os.path.join(selfDir, pluginType + "s", pluginName)

        indexDict = None
        with open(os.path.join(pluginDir, "__index__.json")) as f:
            indexDict = json.load(f)

        if pluginType == "app":
            return AppPlugin(pluginDir, indexDict)
        elif pluginType == "strait":
            return StraitPlugin(pluginDir, indexDict)
        else:
            assert False


class AppPlugin:

    def __init__(self, appDir, indexDict):
        self._dir = appDir

        self._name = indexDict["name"]

        self._straits = indexDict["straits"]

        try:
            exec("from .apps.%s import %s as TmpClass" % (os.path.basename(self._dir), indexDict["class"]))
            self._class = eval("TmpClass")
            assert issubclass(self._class, AppBase)
        except ModuleNotFoundError:
            assert False

    @property
    def name(self):
        return self._name

    @property
    def straits(self):
        return self._straits


class StraitPlugin:
    
    def __init__(self, straitDir, indexDict):
        self._dir = straitDir

        self._name = indexDict["name"]

        try:
            exec("from .straits.%s import %s as TmpClass" % (os.path.basename(self._dir), indexDict["class"]))
            self._class = eval("TmpClass")
            assert issubclass(self._class, StraitBase)
        except ModuleNotFoundError:
            assert False

    @property
    def name(self):
        return self._name
